package com.xqnode.boot.handler;

import com.xqnode.boot.common.JsonResult;
import com.xqnode.boot.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 异常统一处理类
 *
 * @author xiaqing
 * @version 1.0
 */
@ControllerAdvice(basePackages = {"com.xqnode.boot.controller"})
public class ApplicationExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationExceptionHandler.class);

    /**
     * @param e HttpMessageNotReadableException
     * @return ErrorResponse
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public JsonResult handleHttpMessage(HttpMessageNotReadableException e) {
        logger.error("请求异常", e);
        return JsonResult.errorResult("请求参数异常");
    }

    /**
     * Description:空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult handleExceptionServer(NullPointerException e) {
        logger.error("空指针异常", e);
        return JsonResult.errorResult("空指针程序异常");
    }

    /**
     * Description:运行程序异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult handleRuntimeException(RuntimeException e) {
        logger.error("运行异常", e);
        return JsonResult.errorResult("运行程序异常");
    }

    /**
     * Description:业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult handleExceptionServer(BusinessException e) {
        logger.error("业务异常", e);
        return JsonResult.errorResult(e.getMessage());
    }

    /**
     * Description:最大异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public JsonResult handleExceptionServer(Exception e) {
        logger.error("程序异常", e);
        return JsonResult.errorResult("程序异常");
    }

}
